// 上游创建/编辑组件
const UpstreamsCreate = {
    template: `
        <div class="form-container">
            <div class="form-header">
                <h2 class="form-title">{{ isEdit ? '编辑上游' : '创建上游' }}</h2>
            </div>
            
            <el-form ref="form" :model="form" :rules="rules" label-width="120px" v-loading="loading">
                <el-form-item label="名称" prop="name">
                    <el-input v-model="form.name" placeholder="上游名称，例如：web-cluster"></el-input>
                </el-form-item>
                
                <el-form-item label="负载均衡算法" prop="type">
                    <el-select v-model="form.type" placeholder="请选择负载均衡算法">
                        <el-option label="轮询" value="roundrobin"></el-option>
                        <el-option label="一致性哈希" value="chash"></el-option>
                        <el-option label="最少连接" value="least_conn"></el-option>
                    </el-select>
                </el-form-item>
                
                <el-form-item label="状态">
                    <el-switch
                        v-model="form.status"
                        active-text="启用"
                        inactive-text="禁用">
                    </el-switch>
                </el-form-item>
                
                <el-form-item label="描述" prop="description">
                    <el-input type="textarea" v-model="form.description" rows="3"></el-input>
                </el-form-item>
                
                <el-form-item label="节点">
                    <div v-for="(node, index) in nodes" :key="index" class="upstream-node">
                        <el-input v-model="node.host" placeholder="主机" style="width: 40%; margin-right: 10px;"></el-input>
                        <el-input-number v-model="node.port" :min="1" :max="65535" placeholder="端口" style="width: 20%; margin-right: 10px;"></el-input-number>
                        <el-input-number v-model="node.weight" :min="0" :max="100" placeholder="权重" style="width: 20%; margin-right: 10px;"></el-input-number>
                        <el-button type="danger" icon="el-icon-delete" circle @click="removeNode(index)"></el-button>
                    </div>
                    <el-button type="primary" icon="el-icon-plus" @click="addNode">添加节点</el-button>
                </el-form-item>
                
                <el-form-item label="健康检查" v-if="showAdvanced">
                    <el-switch v-model="healthCheck.enabled"></el-switch>
                </el-form-item>
                
                <template v-if="healthCheck.enabled && showAdvanced">
                    <el-form-item label="检查类型">
                        <el-radio-group v-model="healthCheck.type">
                            <el-radio label="http">HTTP</el-radio>
                            <el-radio label="tcp">TCP</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    
                    <template v-if="healthCheck.type === 'http'">
                        <el-form-item label="HTTP路径">
                            <el-input v-model="healthCheck.http_path" placeholder="/health"></el-input>
                        </el-form-item>
                        
                        <el-form-item label="期望状态码">
                            <el-input v-model="healthCheck.healthy.http_statuses" placeholder="200,201,204"></el-input>
                        </el-form-item>
                    </template>
                    
                    <el-form-item label="检查间隔(秒)">
                        <el-input-number v-model="healthCheck.interval" :min="1" :max="300"></el-input-number>
                    </el-form-item>
                    
                    <el-form-item label="超时(秒)">
                        <el-input-number v-model="healthCheck.timeout" :min="1" :max="60"></el-input-number>
                    </el-form-item>
                </template>
                
                <el-form-item>
                    <el-button type="text" @click="showAdvanced = !showAdvanced">
                        {{ showAdvanced ? '隐藏高级选项' : '显示高级选项' }}
                        <i :class="showAdvanced ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"></i>
                    </el-button>
                </el-form-item>
                
                <div class="form-footer">
                    <el-button @click="goBack">取消</el-button>
                    <el-button type="primary" @click="submitForm">{{ isEdit ? '保存' : '创建' }}</el-button>
                </div>
            </el-form>
        </div>
    `,
    props: {
        id: {
            type: [String, Number],
            required: false
        }
    },
    data() {
        return {
            form: {
                name: '',
                type: 'roundrobin',
                status: true,
                description: ''
            },
            nodes: [
                { host: '', port: 80, weight: 1 }
            ],
            healthCheck: {
                enabled: false,
                type: 'http',
                http_path: '/health',
                interval: 5,
                timeout: 3,
                healthy: {
                    http_statuses: '200,201,204'
                }
            },
            showAdvanced: false,
            loading: false,
            rules: {
                name: [
                    { required: true, message: '请输入上游名称', trigger: 'blur' },
                    { pattern: /^[a-z0-9-_]+$/, message: '上游名称只能包含小写字母、数字、连字符和下划线', trigger: 'blur' }
                ],
                type: [
                    { required: true, message: '请选择负载均衡算法', trigger: 'change' }
                ]
            }
        };
    },
    computed: {
        isEdit() {
            return !!this.id;
        }
    },
    created() {
        if (this.isEdit) {
            this.fetchUpstream();
        }
    },
    methods: {
        fetchUpstream() {
            this.loading = true;
            
            // 模拟获取上游数据
            setTimeout(() => {
                const upstream = {
                    id: this.id,
                    name: "web-cluster",
                    type: "roundrobin",
                    status: true,
                    description: "Web服务器集群",
                    nodes: {
                        "web1.example.com:80": 1,
                        "web2.example.com:80": 1,
                        "web3.example.com:80": 1
                    },
                    checks: {
                        active: {
                            type: "http",
                            http_path: "/health",
                            healthy: {
                                interval: 5,
                                http_statuses: [200, 201, 204]
                            },
                            timeout: 3
                        }
                    }
                };
                
                // 填充表单数据
                this.form.name = upstream.name;
                this.form.type = upstream.type;
                this.form.status = upstream.status;
                this.form.description = upstream.description;
                
                // 处理节点数据
                this.nodes = [];
                if (upstream.nodes) {
                    Object.entries(upstream.nodes).forEach(([target, weight]) => {
                        const [host, port] = target.split(':');
                        this.nodes.push({
                            host,
                            port: parseInt(port),
                            weight
                        });
                    });
                }
                
                // 处理健康检查数据
                if (upstream.checks && upstream.checks.active) {
                    this.healthCheck.enabled = true;
                    this.healthCheck.type = upstream.checks.active.type;
                    
                    if (upstream.checks.active.type === 'http') {
                        this.healthCheck.http_path = upstream.checks.active.http_path;
                        
                        if (upstream.checks.active.healthy && upstream.checks.active.healthy.http_statuses) {
                            this.healthCheck.healthy.http_statuses = upstream.checks.active.healthy.http_statuses.join(',');
                        }
                    }
                    
                    if (upstream.checks.active.healthy) {
                        this.healthCheck.interval = upstream.checks.active.healthy.interval;
                    }
                    
                    this.healthCheck.timeout = upstream.checks.active.timeout;
                    
                    // 显示高级选项
                    this.showAdvanced = true;
                }
                
                this.loading = false;
            }, 500);
        },
        addNode() {
            this.nodes.push({ host: '', port: 80, weight: 1 });
        },
        removeNode(index) {
            this.nodes.splice(index, 1);
        },
        submitForm() {
            this.$refs.form.validate(valid => {
                if (valid) {
                    // 验证至少有一个有效节点
                    const validNodes = this.nodes.filter(node => node.host && node.port);
                    if (validNodes.length === 0) {
                        this.$message.error('请至少添加一个有效的上游节点');
                        return;
                    }
                    
                    // 构建提交数据
                    const formData = {
                        name: this.form.name,
                        type: this.form.type,
                        status: this.form.status,
                        description: this.form.description,
                        nodes: {}
                    };
                    
                    // 处理节点数据
                    validNodes.forEach(node => {
                        formData.nodes[`${node.host}:${node.port}`] = node.weight;
                    });
                    
                    // 处理健康检查数据
                    if (this.healthCheck.enabled) {
                        formData.checks = {
                            active: {
                                type: this.healthCheck.type,
                                timeout: this.healthCheck.timeout,
                                healthy: {
                                    interval: this.healthCheck.interval
                                }
                            }
                        };
                        
                        if (this.healthCheck.type === 'http') {
                            formData.checks.active.http_path = this.healthCheck.http_path;
                            
                            if (this.healthCheck.healthy.http_statuses) {
                                formData.checks.active.healthy.http_statuses = this.healthCheck.healthy.http_statuses
                                    .split(',')
                                    .map(status => parseInt(status.trim()))
                                    .filter(status => !isNaN(status));
                            }
                        }
                    }
                    
                    this.loading = true;
                    
                    // 模拟API调用
                    setTimeout(() => {
                        this.$message({
                            message: this.isEdit ? '更新成功！' : '创建成功！',
                            type: 'success'
                        });
                        this.goBack();
                    }, 500);
                }
            });
        },
        goBack() {
            this.$router.push('/upstreams/list');
        }
    }
}; 